package com.zxy.furns.service.impl;

import com.zxy.furns.dao.FurnDAO;
import com.zxy.furns.dao.OrderDAO;
import com.zxy.furns.dao.OrderItemDAO;
import com.zxy.furns.dao.impl.FurnDAOImpl;
import com.zxy.furns.dao.impl.OrderDAOImpl;
import com.zxy.furns.dao.impl.OrderItemImpl;
import com.zxy.furns.entity.*;
import com.zxy.furns.service.OrderService;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * ClassName: OrderServiceImpl
 * Package: com.zxy.furns.service.impl
 *
 * @Author zxy
 * @Create 2025/3/25 23:40
 * @Version 1.0
 * title:
 * Description:
 */
public class OrderServiceImpl implements OrderService {
    private OrderDAO orderDAO = new OrderDAOImpl();
    private OrderItemDAO orderItemDAO = new OrderItemImpl();
    private FurnDAO furnDAO = new FurnDAOImpl();

    @Override
    public String saveOrder(Cart cart, int memberId) {
        //生成订单号，要求唯一的
        String orderId = System.currentTimeMillis() + "" + memberId;
        Order order = new Order(orderId, new Date(), cart.getCartTotalPrice(), 0, memberId);
        //保存到Order
        orderDAO.saveOrder(order);
        //处理订单项，这里的订单项是根据我们的购物车项来确定的
        //所以先获取购物车项
        Map<Integer, CartItem> items = cart.getItems();
        Set<Integer> keys = items.keySet();
        for (Integer id : keys) {
            //获取到购物车的每一项
            CartItem item = items.get(id);
            OrderItem orderItem = new OrderItem(null, item.getName(), item.getPrice(), item.getCount(), item.getTotalPrice(), orderId);
            orderItemDAO.saveOrderItem(orderItem);//保存到订单项
            //更新furn表中的库存和销量
            Furn furn = furnDAO.queryFurnById(id);
            furn.setStock(furn.getStock() - item.getCount());
            furn.setSales(furn.getSales() + item.getCount());
            //更新furn数据表
            furnDAO.updateFurn(furn);
        }

        //清空购物车
        items.clear();
        return orderId;

    }

    @Override
    public List<Order> listOrder(int memberId) {
        return orderDAO.listOrder(memberId);
    }

    @Override
    public List<OrderItem> listOrderItem(String orderId) {
        return orderItemDAO.listOrderItem(orderId);
    }


}
